<?php

namespace App\Policies\Admin;

use App\Models\Question;
use App\Models\Role;
use App\Models\User;
use Exception;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;

class QuestionPolicy
{
    use HandlesAuthorization;

    /**
     * 超级管理员可以有任何操作
     *
     * @param User $user
     * @return mixed
     * @throws Exception
     */
    public function before(User $user)
    {
        return $user->hasRole(Role::SUPER_ADMIN) || $user->hasAnyPermission(['questions']);
    }

    /**
     * Determine whether the user can view any models.
     *
     * @param User $user
     * @return mixed
     * @throws Exception
     */
    public function viewAny(User $user)
    {
        // 检查是否有题库管理和题库列表的权限
        return $user->hasAnyPermission(['questions', 'questions.index']);
    }

    /**
     * Determine whether the user can view the model.
     *
     * @param User $user
     * @param Question $question
     * @return mixed
     * @throws Exception
     */
    public function view(User $user, Question $question)
    {
        return $user->id === $question->user_id && $user->hasAnyPermission(['questions', 'questions.show']);
    }

    /**
     * Determine whether the user can create models.
     *
     * @param User $user
     * @return mixed
     * @throws Exception
     */
    public function create(User $user)
    {
        return $user->hasAnyPermission(['questions', 'questions.store']);
    }

    /**
     * Determine whether the user can update the model.
     *
     * @param User $user
     * @param Question $question
     * @return mixed
     * @throws Exception
     */
    public function update(User $user, Question $question)
    {
        return $user->id === $question->user_id && $user->hasAnyPermission(['questions', 'questions.update']);
    }

    /**
     * Determine whether the user can delete the model.
     *
     * @param User $user
     * @param Question $question
     * @return mixed
     * @throws Exception
     */
    public function delete(User $user, Question $question)
    {
        return $user->id === $question->user_id && $user->hasAnyPermission(['questions','questions.destroy']);
    }
}
